package com.kuhyygy.service;


import java.util.Random;

import com.kuhyygy.bean.QueueMsg;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class MsgQueueService extends Service {
	
	private static final String TAG = MsgQueueService.class.getName();
	private Handler handler;
	
	public static final int MSG_A = 1;
	public static final int MSG_B = 2;
	
	public MsgQueueService() {
		Log.i(TAG, "create instance");
	}
	
	private class MsgHandler extends Handler {
		
		public MsgHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_A:
				QueueMsg qm = (QueueMsg)msg.obj;
				Log.i(TAG, "MSG_A...");
				Log.i(TAG, qm.getName() + "--" + qm.getAge());
				break;
			case MSG_B:
				Log.i(TAG, "MSG_B...");
				break;
			default:
				break;
			}
			stopSelf(msg.arg1);
		}
		
	}
	
	@Override
	public void onCreate() {
		Looper looper = Looper.getMainLooper();
		handler = new MsgHandler(looper);
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Message msg = handler.obtainMessage();
		Random rand = new Random();
		msg.what = MSG_A;
		msg.arg1 = startId;
		QueueMsg qm = new QueueMsg();
		qm.setName("user" + rand.nextInt(70));
		qm.setAge(rand.nextInt(70));
		msg.obj = qm;
		handler.sendMessage(msg);
		return super.onStartCommand(intent, flags, startId);
	}



	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	public Handler getHandler() {
		return handler;
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

}
